package cn.pconline.officialclub.web;

import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.service.IntfService;
import cn.pconline.autoclub.util.Regex;
import cn.pconline.autoclub.util.Result;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.r.client.EntityBuilder;
import cn.pconline.r.client.ResponseExtractor;
import cn.pconline.r.client.SimpleHttpTemplate;
import com.alibaba.fastjson.JSONObject;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.StatusLine;
import org.apache.http.util.EntityUtils;
import org.gelivable.dao.GeliDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * 依赖外部接口相关的功能
 *
 * @author <a href="mailto:chensy0203@163.com">chensy</a>
 */
@Controller
@RequestMapping("/brand/intf")
public class IntfController extends WebKit {

    @Autowired
    private SimpleHttpTemplate simpleHttpTemplate;
    @Autowired
    private GeliDao geliDao;
    @Autowired
    private IntfService intfService;
    /**
     * 返回验证结果，如果为空串就表示验证通过，否则返回验证信息
     *
     * @param phone
     * @param code
     * @return
     */
    private String checkPhoneCode(String phone, String code) {
        String relUrl = systemConfig.getRoot() + "/ClubController.found.checkPhoneCode";
        String url = systemConfig.getCheckCodeUrl();
        String result = simpleHttpTemplate.post(url, relUrl, null,
                new ResponseExtractor<String>() {
                    @Override
                    public String extractData(HttpResponse response) {
                        StatusLine statusLine = response.getStatusLine();
                        if (statusLine.getStatusCode() == 200) {
                            try {
                                return EntityUtils.toString(response.getEntity());
                            } catch (IOException ex) {
                                log.error("checkPhoneCode fail !IOException", ex);
                            } catch (ParseException ex) {
                                log.error("checkPhoneCode fail !ParseException", ex);
                            }
                        } else {
                            log.error("checkPhoneCode fail statusCode is " + statusLine.getStatusCode());
                            try {
                                log.error(EntityUtils.toString(response.getEntity()));
                            } catch (IOException ex) {
                                log.error("checkPhoneCode fail !IOException", ex);
                            } catch (ParseException ex) {
                                log.error("checkPhoneCode fail !ParseException", ex);
                            }
                        }
                        return null;
                    }
                },
                EntityBuilder.entity().param("type", "autoClub").param("act", "check").param("mobile", phone).param("verificationCode", code).build(),
                3000);
        JSONObject rs = JSONObject.parseObject(result);
        if (rs == null) {
            return "手机验证出错，请稍后重试";
        }
        int c = rs.getIntValue("code");
        if (c == 0) {
            return "";
        }
        return rs.getString("message");
    }

    @RequestMapping(value = "/bindPhone.do", method = RequestMethod.POST)
    public void bindPhone(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        User user = checkUser(req, resp);
        if (user == null) {
            return;
        }
        String phone = WebUtils.paramTrim(req, "phone", "");
        if (StringUtils.isBlank(phone)) {
            printMsg(resp, Result.error("请填写手机"));
            return;
        }
        if (!phone.matches(Regex.cellphone.value) || phone.matches(Regex.specialPhone.value)) {
            printMsg(resp, Result.error("请填写合法的手机"));
            return;
        }
        String code = WebUtils.paramTrim(req, "code", "");
        if (StringUtils.isBlank(code)) {
            printMsg(resp, Result.error("请输入验证码"));
            return;
        }
        if (systemConfig.isNeedCheckCode()) {
            String checkCodeMsg = checkPhoneCode(phone, code);
            if (StringUtils.isNotEmpty(checkCodeMsg)) {
                printMsg(resp, Result.error(checkCodeMsg));
                return;
            }
        }
        String commonSessionId = WebUtils.cookie(req, systemConfig.getUserSessionName());
        JSONObject result = intfService.bindPhone(phone, code, commonSessionId);
        if(result!=null){
            if(result.getIntValue("code")==0){
               user.setBindPhone(phone);
               user.setIsSyncdPhone(User.IS_SYNC_PHONE);
               int count = geliDao.update(user, "bind_phone,is_sync_phone");
               if(count>0){
                   printMsg(resp, Result.success("绑定成功！"));
                   return;
               }   
            }
            printMsg(resp, Result.error(result.getString("message")));
        }else{
            printMsg(resp, Result.error("绑定失败!"));
        }
        
    }

    /**
     * 实时获取短信验证码防刷KEY
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "/getVCodeKey", method = RequestMethod.GET)
    public void getVCodeKey(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        String Vkey = "sendVerificationCode.jsp";
        long vCodeTime = System.currentTimeMillis();
        String vCodeKey = WebUtils.md5(Vkey + vCodeTime);
        Result rs = Result.instance().set("vCodeKey", vCodeKey).set("vCodeTime", vCodeTime);
        printMsg(resp, Result.success(rs));
    }
    
}
